package ctrhost

import (
    "github.com/astaxie/beego/logs"
    "strings"
    "fmt"
    "time"
    "cloud_worm/util/umodels/mysqldb"
    "cloud_worm/util/umodels/mysqldb/dbmanager"
    "cloud_worm/util/umodels/mysqldb/dbtask"
    "cloud_worm/util/uid"
    "cloud_worm/util/uhttp"
    "cloud_worm/wormweb/controllers/ctrconfig"
    "cloud_worm/wormweb/controllers/ctrutil"
    "cloud_worm/util/uconst"
)

type MachineWeaponTaskController struct {
    ctrconfig.LoginCtr
}

/**
 创建check task
 */
func (m *MachineWeaponTaskController) Create()  {
    m.Manager()

    type InputInfo struct {
        Comment         string      `json:"comment"`
        IP              string      `json:"ip"`                 // 必填，
        WormId          string      `json:"worm_id"`            // 必填，
        Weapons         string      `json:"weapons"`            // 必填，涉及的weapon，采用","号分割，weapon name
    }
    var input InputInfo
    if err := m.Unmarshal(&input); err != nil {
        m.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, err.Error(), nil)
        m.ServeJSON()
        return
    }

    if input.IP == mysqldb.SelectStrAll || len(input.WormId) != uconst.AgentIdLen {
        logs.Warn("input ip or worm id error.")
        data := map[string]interface{}{"total": 0, "data": []dbtask.WeaponTask{}}
        m.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input machine ip or worm id error.", data)
        m.ServeJSON()
        return
    }
    var taskWps []string
    for _, item := range strings.Split(strings.TrimSpace(input.Weapons), ",") {
        item = strings.TrimSpace(item)
        if item != "" {
            taskWps = append(taskWps, item)
        }
    }
    if len(taskWps) == 0 {
        logs.Warn("no input weapon")
        data := map[string]interface{}{"total": 0, "data": []dbtask.WeaponTask{}}
        m.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "no input weapon", data)
        m.ServeJSON()
        return
    }
    // 匹配主机machine
    machine := &dbmanager.Machine{Ip: input.IP, WormId: input.WormId, Status: mysqldb.StatusValid}
    if err := machine.Read("ip", "worm_id", "status"); err != nil {
        logs.Warn(fmt.Sprintf("destination machine no valid: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbtask.WeaponTask{}}
        m.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "destination machine no valid", data)
        m.ServeJSON()
        return
    }

    // 准备插入数据
    task := &dbtask.WeaponTask{
        TaskId:      uid.TaskIdProducer().CreateTaskId(),
        TaskOwner:   m.UserInfo.Username,
        TargetType:  ctrutil.TaskForMachine,
        Target:      machine.Ip,
        WeaponsName: strings.Join(taskWps, ","),
        Comment:     input.Comment,
        SumCount:    len(taskWps),
        Created:     time.Now().Unix(),
        Status:      ctrutil.WEAPON_TASK_NO_DO,
    }
    task.Updated = task.Created
    if err :=  task.Insert(); err != nil {
        logs.Warn(fmt.Sprintf("insert task error: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbtask.WeaponTask{}}
        m.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "insert task error.", data)
        m.ServeJSON()
        return
    }

    // 成功插入之后的结果返回
    var tasks []dbtask.WeaponTask
    tasks = append(tasks, *task)
    data := map[string]interface{}{"total": 1, "data": tasks}
    m.Data["json"] = uhttp.CreateOkResponse(data)
    m.ServeJSON()
    return
}
